package blow.sky.quoted.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Description 邮件发送工具
 * @Author 孙焰明
 * @Date 2021/5/20 10:35
 */

@Component
public class EmailUtil
{
	@Autowired
	private JavaMailSender mailSender;
	// 发送者
	@Value("${spring.mail.username}")
	private String from;

	/**
	 * 发送HTML格式的邮件
	 * @param content 邮件内容
	 * @return
	 */
	public boolean sendHTMLEmail(EmailContent content)
	{
		MimeMessage message = null;
		try {
			message = mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
			messageHelper.setFrom(from);
			messageHelper.setTo(content.getTo());
			messageHelper.setSubject(content.getSubject());
			messageHelper.setText(content.getContent(), true);
			mailSender.send(message);
			return true;
		}
		catch (MessagingException e) {
			e.printStackTrace();
		}
		catch (MailException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 发送邮件
	 * @param content 邮件内容
	 * @return
	 */
	public boolean sendEmail(EmailContent content)
	{
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(content.getTo());
		message.setSubject(content.getSubject());
		message.setText(content.getContent());
		try {
			mailSender.send(message);
			return true;
		}
		catch (MailException e) {
			e.printStackTrace();
		}
		return false;
	}
}
